<?php
class Code{
	//用来提取验证文字的子符串
	public $str = 'abcdefghijklmnpqrstuvwsyz123456789';
	//数量
	public $len = 6;
	//宽度
	public $width =100;
	//高度
	public $height=30;
	//背景颜色
	public $bgColor='#dc22ad';
	//文字颜色
	public $textColor='#333333';
	//字体大小
	public $textSize = 16;
	//字体文件
	public $fontFile='font.ttf';

	//最终提取的验证码字符
	public $code;
	//图像资源
	public $img;

	public function __construct(){}

	public function show()
	{
		//创建画布
		$this->createImg();

		//提取验证码字符
		$this->setCodeStr();
		
		//向图片上写入验证码文字
		$this->createText();

		//画干扰线
		$this->createLine();

		//输出显示
		header("Content-type:image/png");
		imagepng($this->img);
	}

	/**
	 * 绘制干扰线
	 * @return [type] [description]
	 */
	private function createLine()
	{
		$color =$this->getColor($this->textColor);
		for($i=0;$i<3;$i++)
		{
			imageline($this->img, 
				mt_rand(0,$this->width), mt_rand(0,$this->height)
				, mt_rand(0,$this->width), mt_rand(0,$this->height), $color);
		}

		for($i=0;$i<30;$i++)
		{
			imagesetpixel($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), $color);
		}
	}
	/**
	 * 向图片中写入验证码文字
	 * @return [type] [description]
	 */
	private function createText()
	{
		$color =$this->getColor($this->textColor);
		//每个字占用的空间宽度
		$w =$this->width/$this->len;
		//循环写入文字
		for($i=0;$i<$this->len;$i++)
		{
		imagettftext($this->img, $this->textSize, 
			mt_rand(-20,20), $w*$i+5, 20+mt_rand(0,10), $color, $this->fontFile, $this->code[$i]);
		}
	}

	/**
	 * 创建画布
	 * @return [type] [description]
	 */
	private function createImg()
	{
		$this->img = imagecreatetruecolor($this->width, $this->height);
		$color = $this->getColor($this->bgColor);
		imagefill($this->img, 0, 0, $color);
		$lineColor =$this->getColor('#aaaaaa');
		imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1, $lineColor);
	}

	/**
	 * 获取验证码字符串
	 * @return [type] [description]
	 */
	private function setCodeStr()
	{
		$code ='';
		for($i=0;$i<$this->len;$i++)
		{
			$pos =mt_rand(0,strlen($this->str)-1);
			$code.=$this->str[$pos];
		}	
		$this->code =  strtoupper($code);
		//记录验证码字符串，用于以后比较
		$_SESSION['code']=$this->code;
	}
	/**
	 * 获取颜色对象
	 * @param  [type] $color [16进制色值]
	 * @return [type]        [颜色对象]
	 */
	private function getColor($color)
	{
		//删除#符号
		$red = hexdec(substr($color,1,2));
		$green = hexdec(substr($color,3,2));
		$blue = hexdec(substr($color,5,2));

		return imagecolorallocate($this->img, $red, $green, $blue);
	}
}





